package com.sxjh.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Component
@Aspect
@Slf4j
public class GlobalAspect {

    //private final String executeExpr = "execution(* com.sxjh..*Controller.*(..))";

    @Pointcut("execution(* com.sxjh..*Controller.*(..))")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求相关参数
        log.info("========================================== Start ==========================================");
        // 打印请求 url
        log.info("===URL: {},,,HTTP Method:{},,,IP:{}", request.getRequestURL().toString(), request.getMethod(), request.getRemoteAddr());
        // 打印请求入参
        if (!"/Callback".equals(request.getRequestURI())) {
            log.info("===Request Args   : {}", joinPoint.getArgs());
        }
    }

    /**
     * 在切点之后织入
     *
     * @throws Throwable
     */
    @After("webLog()")
    public void doAfter() throws Throwable {
        //log.info("=========================================== End ===========================================");
        // 每个请求之间空一行
        //log.info("");
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MDC.put("TRACE_ID", UUID.randomUUID().toString().replace("-", ""));
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        //log.info("Response Args  : {}", JSON.toJSON(result));
        // 执行耗时
        log.info("===Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        log.info("=========================================== End ===========================================");
        MDC.clear();
        return result;
    }
}
